/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean;

import java.io.InputStream;
import java.io.Serializable;
import java.sql.ResultSet;
import java.util.HashMap;
import javax.enterprise.context.SessionScoped;
import javax.sql.DataSource;
import javax.annotation.Resource;
import javax.inject.Named;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperRunManager;


/**
 *
 * @author Woon Yong
 */
@ManagedBean(name="salesLeadReportBean") 
@Named(value = "salesLeadReportBean")
@SessionScoped
public class SalesLeadReportBean implements Serializable {
    @Resource(name = "macteamData")
    private DataSource macteamData;

    /** Creates a new instance of SalesLeadReportBean */
    public SalesLeadReportBean() {
    }
    
    public void exportReportToPdf() {
        
        try
{
            String strSQL = "SELECT saleslead.`ID`, saleslead.`ARCHIVED`, saleslead.`COMPANYNAME`, saleslead.`CREATEDAT`, saleslead.`FIRSTNAME`, saleslead.`JOBTITLE`, saleslead.`LASTNAME`, saleslead.`TITLE`" + 
            "FROM `saleslead` saleslead";
            
            ResultSet rsEvents = macteamData.getConnection().prepareStatement(strSQL).executeQuery();
            JRResultSetDataSource jrResultSetDataSource = new JRResultSetDataSource(rsEvents);

            //InputStream reportStream = ((HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(true)).getServletContext().getResourceAsStream(null);
            InputStream reportStream = ((HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(true)).getServletContext().getResourceAsStream("/jasperreports/salesLeadReport.jasper");
            
            ((HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse()).setContentType("application/pdf");     
            ServletOutputStream outputStream = ((HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse()).getOutputStream();
            HashMap jasperParameter = new HashMap();
        
            jasperParameter.put("IMAGEPATH", "https://localhost:8181/MacTeam-war/jasperreports/cherry.jpg");
            JasperRunManager.runReportToPdfStream(reportStream, outputStream, jasperParameter, jrResultSetDataSource);
            

            outputStream.flush();

            outputStream.close();
            
            }

        catch (JRException jrex)

        {

            System.out.println("********** Jasperreport Exception");

            jrex.printStackTrace();

        }

        catch (Exception ex)

        {

            ex.printStackTrace();

        }
}
    
    
    
}


